package com.zhoutao123.hephaestus.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class JSONUtils {
  public static final ObjectMapper jsonObjectMapper = new ObjectMapper();

  public static <T> T readJSON(String json, Class<T> clazz) throws IOException {
    return jsonObjectMapper.readValue(json, clazz);
  }

  public static <T> T readJSON(String json, TypeReference<T> typeReference) throws IOException {
    if(json == null){
      return null;
    }
    return jsonObjectMapper.readValue(json, typeReference);
  }

  /** 将序列化错误封装成运行时错误，期望调用者传入可序列化的数据 */
  public static <T> String toJSONString(T object) {
    try {
      return jsonObjectMapper.writeValueAsString(object);
    } catch (JsonProcessingException e) {
      throw new RuntimeException(e);
    }
  }

  public static <T> T readJSON(String json, Class<T> clazz, T defaultValue) {
    try {
      return readJSON(json, clazz);
    } catch (IOException e) {
      log.warn("JSON 读取错误: {}\n{}\n默认值：{}", clazz, json, defaultValue);
      log.warn("JSON 读取错误 Stacktrace", e);
      return defaultValue;
    }
  }

  public static <T> T readJSON(String json, TypeReference<T> typeReference, T defaultValue) {
    try {
      return readJSON(json, typeReference);
    } catch (IOException e) {
      log.warn("JSON 读取错误: {}\n{}\n默认值：{}", typeReference, json, defaultValue);
      log.warn("JSON 读取错误 Stacktrace", e);
      return defaultValue;
    }
  }
}
